package com.allen.retrofit2_rxjava2.view.selectImage;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.retrofit2_rxjava2.R;
import com.allen.retrofit2_rxjava2.base.TitleViewActivity;
import com.allen.retrofit2_rxjava2.view.selectImage.adapter.GalleryPagerAdapter;
import com.allen.retrofit2_rxjava2.view.selectImage.adapter.UploadVideoImageAdapter;
import com.allen.retrofit2_rxjava2.view.selectImage.entity.ChooseUploadParam;
import com.allen.retrofit2_rxjava2.view.selectImage.view.HackyProblematicViewPager;
import com.allen.retrofit2_rxjava2.view.selectimageview.PhotoActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

public class PreviewUploadActivity extends TitleViewActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, GalleryPagerAdapter.OnVideoItemClickListener {

    private static final String TAG = "preview";

    private HackyProblematicViewPager vp_gallery;
    private GalleryPagerAdapter adapter;
    private RelativeLayout rl_bottom;
    private AppCompatCheckBox cb;
    private ArrayList<ChooseUploadParam> selectingParams;
    private ArrayList<ChooseUploadParam> datas;
    //还能上传的最大文件数
    private int maxLeftCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_preview);
        initView();
        initHeader();
        initData();
//        setNotFullScreen();
    }

    private void initHeader() {
        initTitleView();
        initLeftBackView(null);
        setRightViewVisible(false);
        setCenterViewContent(getResources().getString(R.string.select_image));
        initRightView(getResources().getString(R.string.preview));
        setRightViewOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                send();//发送
            }
        });
    }

    private void initView() {
        vp_gallery = (HackyProblematicViewPager) findViewById(R.id.vp_gallery);
        vp_gallery.addOnPageChangeListener(this);
        rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        cb = (AppCompatCheckBox) findViewById(R.id.cb);
        cb.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        maxLeftCount = intent.getIntExtra("maxLeftCount", 3);
        int initPosition = intent.getIntExtra("initPosition", 0);
        datas = intent.getParcelableArrayListExtra("data");
        selectingParams = intent.getParcelableArrayListExtra("select");
        adapter = new GalleryPagerAdapter(this, datas);
        adapter.setOnVideoItemClickListener(this);
        vp_gallery.setAdapter(adapter);
        vp_gallery.setCurrentItem(initPosition);
        setCenterViewContent((initPosition + 1) + "/" + datas.size());
        cb.setChecked(isSelected(datas.get(initPosition)));
        setText();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cb:
                checkCbValid();
                break;
            default:
                Intent intent = getIntent();
                intent.putParcelableArrayListExtra("data", selectingParams);
                setResult(SelectPhotoActivity.REQUEST_PHONE, intent);
                finish();
                break;
        }
    }

    private void checkCbValid() {
        int position = vp_gallery.getCurrentItem();
        ChooseUploadParam param = datas.get(position);
        if (cb.isChecked()) {
            selectingParams.add(param);
            if (param.getType() == UploadVideoImageAdapter.TYPE_VIDEO && over2Video()) {
                selectingParams.remove(param);
                cb.toggle();
                Toast.makeText(this, "只允许上传一个视频！", Toast.LENGTH_SHORT).show();
                return;
            }

        } else {
            removeParam(param);
        }
        setText();
    }

    private void removeParam(ChooseUploadParam param) {
        Iterator<ChooseUploadParam> iterator = selectingParams.iterator();
        while (iterator.hasNext()) {
            if (param.getPath().equals(iterator.next().getPath())) {
                iterator.remove();
            }
        }
    }

    private void send() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra("data", selectingParams);
        if (selectingParams.size() == 0) {
            setResult(RESULT_CANCELED, intent);
        } else {
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    private void playVideo(String path) {
        Log.d(TAG, "要播放的视频地址：" + path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "video/*";
        Uri uri = Uri.fromFile(new File(path));
        intent.setDataAndType(uri, type);
        startActivity(intent);
    }

    @Override
    public void onPageSelected(int position) {
        ArrayList<ChooseUploadParam> params = adapter.getParams();
        setCenterViewContent((position + 1) + "/" + params.size());
        ChooseUploadParam param = params.get(position);
        cb.setChecked(isSelected(param));
    }

    private boolean isSelected(ChooseUploadParam currentParam) {
        for (ChooseUploadParam param : selectingParams) {
            if (currentParam.getPath().equals(param.getPath())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }
    //设置全屏
    private void setFullScreen() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(params);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setTitleVisibility(false);
        rl_bottom.setVisibility(View.GONE);
    }
    //设置全屏
    private void setNotFullScreen() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setTitleVisibility(true);
        rl_bottom.setVisibility(View.VISIBLE);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    @Override
    public void onVideoItemClick(String path) {
        playVideo(path);
    }

    private void setText() {
        String text_send = "添加(" + selectingParams.size() + "/" + maxLeftCount + ")";
        if (selectingParams.size() == 0) {
            setRightViewVisible(false);
        } else {
            setRightViewVisible(true);
        }
        initRightView(text_send);
    }

    public boolean over2Video() {
        int videoCount = 0;
        for (ChooseUploadParam param : selectingParams) {
            if (param.getType() == UploadVideoImageAdapter.TYPE_VIDEO) {
                videoCount++;
            }
        }
        return videoCount > 1;
    }
}
